<!--
 * @Author: your name
 * @Date: 2021-09-15 12:07:57
 * @LastEditTime: 2021-09-16 18:54:47
 * @LastEditors: hucc
 * @Description: In User Settings Edit
 * @FilePath: \briup\6-jQuery\day04\8-socket.html
-->
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>socket</title>
    <script src="../js/jquery.js"></script>
</head>

<body>
    ip:<input type="text" name="ip" value="47.94.46.113">
    <br/> port:
    <input type="text" name="port" value="8888">
    <br/> path:
    <input type="text" name="path" value="/imserver/1">
    <button id="open-btn">打开连接</button>
    <button id="close-btn">关闭连接</button>
    <div id="msg"></div>
</body>
<script>
    var socket;
    $(function() {
        $("#open-btn").click(openSocket);
        $("#close-btn").click(openSocket);
    })

    function closeSocket() {
        socket.close();
    }

    function openSocket() {
        if (typeof(WebSocket) === "undefined") {
            alert("浏览器不支持")
        }
        var ip = $("input[name=ip]").val();
        var port = $("input[name=port]").val();
        var path = $("input[name=path]").val();
        socket = new WebSocket("ws://" + ip + ":" + port + path);
        socket.onopen = function() {
            $("#msg").text("socket已经打开");
        }
        socket.onmessage = function(msg) {
            console.log(msg.data);
            $("#msg").text("socket后台发来消息" + msg.data);
        }
    }
</script>

</html> }
    }
</script>

</html>